﻿using System.Linq;
using Wombat.Core.Extensions;
using Wombat.Core.Factories;
using Wombat.Core.Services;
using Wombat.Data.Model;
using IDataService = Wombat.Core.Services.IDataService;

namespace Wombat.Core.Gates
{
    public class FloatStorageGate: StorageBaseGate
    {
        public delegate FloatStorageGate Factory();

        private readonly ITagStateService _tagStateService;

        public FloatStorageGate(IConfigurationService configService, IDataService databaseService, ITagRpository tagRpository, ITagStateService tagStateService) : base(configService, databaseService, tagRpository)
        {
            _tagStateService = tagStateService;
            DataIn = (IObserverPort<ITagValue>)PortFactory.Create<ITagValue>("DataIn", PortBehavior.Input, OnNextData);
        }

        public readonly IObserverPort<ITagValue> DataIn;

        protected override void SetupPorts()
        {
            {
                Ports = new[]
                        {
                            DataIn
                        }.ToList();
            }
        }

        async private void OnNextData(ITagValue tagValue)
        {
            await DatabaseService.InsertFloatDataAsync(FloatDataFromTagValue((ITagValue<double?>)tagValue));
        }

        private FloatData FloatDataFromTagValue(ITagValue<double?> tagValue)
        {
            var leftDeviation = _tagStateService.GetLeftDeviation(tagValue.TagId, tagValue.Time, tagValue.Value);
            var floatData = new FloatData
                {
                    TagId = TagRpository.Get(tagValue.TagId).PersistedId,
                    Value = tagValue.Value, LeftDeviation = leftDeviation,
                    Time = tagValue.Time
                };
            return floatData;
        }
    }
}
